<template>
  <div class="app-container">
    <el-button
      :loading="downloadLoading"
      style="margin-bottom:20px"
      type="primary"
      icon="el-icon-document"
      @click="handleDownload"
    >导出Excel
    </el-button>
    <el-button
      :loading="addLoading"
      style="margin-bottom:20px"
      type="primary"
      icon="el-icon-document"
      @click="addFormVisible = true"
    >添加受测者
    </el-button>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="mac" label="mac"/>
      <el-table-column prop="name" label="姓名"/>
      <el-table-column prop="height" label="height"/>
      <el-table-column prop="weight" label="weight"/>
      <el-table-column prop="birth" label="birth"/>
      <el-table-column prop="serial" label="serial"/>
      <el-table-column prop="firmwareVersion" label="firmwareVersion"/>
      <el-table-column prop="softVersion" label="softVersion"/>
      <el-table-column prop="appVersion" label="appVersion"/>
      <el-table-column prop="trousersId" label="trousersId"/>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="button" size="small" @click="handleClick(scope.row)">查看</el-button>
          <el-button type="button" size="small" @click="handleUpload(scope.row)">上传数据</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog title="添加受测者" :visible.sync="addFormVisible">
      <el-form :model="form">
        <el-form-item label="MAC" :label-width="addFormLabelWidth">
          <el-input v-model="form.mac"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="addFormLabelWidth">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="height" :label-width="addFormLabelWidth">
          <el-input v-model="form.height"></el-input>
        </el-form-item>
        <el-form-item label="weight" :label-width="addFormLabelWidth">
          <el-input v-model="form.weight"></el-input>
        </el-form-item>
        <el-form-item label="birth" :label-width="addFormLabelWidth">
          <el-input v-model="form.birth"></el-input>
        </el-form-item>
        <el-form-item label="serial" :label-width="addFormLabelWidth">
          <el-input v-model="form.serial"></el-input>
        </el-form-item>
        <el-form-item label="firmwareVersion" :label-width="addFormLabelWidth">
          <el-input v-model="form.firmwareVersion"></el-input>
        </el-form-item>
        <el-form-item label="softVersion" :label-width="addFormLabelWidth">
          <el-input v-model="form.softVersion"></el-input>
        </el-form-item>
        <el-form-item label="appVersion" :label-width="addFormLabelWidth">
          <el-input v-model="form.appVersion"></el-input>
        </el-form-item>
        <el-form-item label="trousersId" :label-width="addFormLabelWidth">
          <el-input v-model="form.trousersId"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addLoading=false;addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd()">添 加</el-button>
      </div>
    </el-dialog>
    <el-dialog title="时间范围选择" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="时间范围选择" :label-width="formLabelWidth">
          <el-date-picker
            v-model="timearea"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="gotoDetail()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="上传数据" :visible.sync="uploadFormVisible">
      <el-form :model="form">
        <el-upload
          class="upload-demo"
          ref="upload"
          accept=".xls, .xlsx"
          action="https://jsonplaceholder.typicode.com/posts/"
          :auto-upload="false"
          :on-change="handleChange"
          :multiple='true'
          :show-file-list='true'
          :file-list="fileList"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xlsx模板文件，且不超过500kb</div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadFormVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getTestuserList, saveTestUser, parsingExcelAddData} from '@/api/testuser'
import {fetchList} from '@/api/article'
import {parseTime} from '@/utils'

import FilenameOption from '@/views/excel/components/FilenameOption'
import AutoWidthOption from '@/views/excel/components/AutoWidthOption'
import BookTypeOption from '@/views/excel/components/BookTypeOption'

export default {

  components: {
    FilenameOption,
    AutoWidthOption,
    BookTypeOption
  },
  data() {
    return {
      tableData: null,
      dialogFormVisible: false,
      addFormVisible: false,
      uploadFormVisible: false,
      form: {
        mac: 'F3:70:71:61:6E:00',
        name: '测试',
        height: '170',
        weight: '60',
        birth: '1989-08-28',
        serial: '3300000001',
        firmwareVersion: '1.0.6',
        softVersion: '1.3.4',
        appVersion: '1.3.8',
        trousersId: '29'
      },
      formLabelWidth: '120px',
      addFormLabelWidth: '120px',
      timearea: [new Date(), new Date()],
      currentPage: 1,
      totalNum: 0,
      selectid: null,

      listLoading: true,
      downloadLoading: false,
      addLoading: false,
      filename: '',
      autoWidth: true,
      bookType: 'xlsx',
      fileList: []
    }
  },
  mounted() {
    this.getdata()
  },
  methods: {
    handleClick(row) {
      this.selectid = row.serial
      this.dialogFormVisible = true
    },
    handleUpload(row) {
      this.selectid = row.serial
      this.uploadFormVisible = true

    },
    getdata() {
      getTestuserList().then(res => {
        this.tableData = res.data.records
        this.totalNum = res.data.total
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    },
    gotoDetail() {
      this.dialogFormVisible = false
      this.$router.push({
        path: '/testuser/detail',
        query: {
          serial: this.selectid,
          starttime: this.timearea[0].getTime(),
          endtime: this.timearea[1].getTime()
        }
      })
    },
    fetchData() {
      this.listLoading = true
      fetchList().then(response => {
        this.list = response.data.items
        this.listLoading = false
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['mac', 'name', 'height', 'weight', 'birth']
        const filterVal = ['mac', 'name', 'height', 'weight', 'birth']
        const list = this.tableData
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    handleAdd() {
      this.addLoading = false;
      this.addFormVisible = false;
      saveTestUser(this.form)
      this.getdata()
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    submitUpload() {
      // this.$refs.upload.submit(); // 原始提交事件
      for (let i = 0; i < this.fileList.length; i++) {
        let fd = new FormData()
        fd.append('data', JSON.stringify(this.form))
        fd.append('fileToUpload', this.fileList[i].raw)
        parsingExcelAddData(fd).then((data) => {
          //处理成功后的逻辑
          console.log(data.code);//这个data 是接收的resolve参数--
        }).catch((err) => {
          console.log(err);
        });
      }
    },
    handleChange(files, fileList) {
      this.fileList = fileList
    },
  }
}
</script>
